<?php
class wechatMpOauth extends OauthBase
{
	private $AppID     = '';
	private $AppSecret = '';

	public function __construct($config)
	{
		$this->AppID     = isset($config['AppID'])     ? $config['AppID']     : "";
		$this->AppSecret = isset($config['AppSecret']) ? $config['AppSecret'] : "";
	}

	public function getFields()
	{
		return array(
			'AppID' => array(
				'label' => 'AppID',
				'type'  => 'string',
			),
			'AppSecret'=>array(
				'label' => 'AppSecret',
				'type'  => 'string',
			),
		);
	}

	//获取登录url地址
	public function getLoginUrl()
	{	
		$urlparam = array(
			"appid=".$this->AppID,
			"redirect_uri=".urlencode(Yun::getUrl()),
			"response_type=code",
			"scope=snsapi_userinfo",
			"state=".rand(100,999),
		);
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?".join("&",$urlparam)."#wechat_redirect";
		return $url;
	}

	//获取进入令牌
	public function getAccessToken($parms)
	{
		$urlparam = array(
			"appid=".$this->AppID,
			"secret=".$this->AppSecret,
			"code=".$parms['code'],
			"grant_type=authorization_code",
		);
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?".join("&",$urlparam);

		//模拟post提交
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$result = curl_exec($ch);
		$tokenInfo = JSON::decode($result);
		if(!$tokenInfo)
		{
			die(var_export($result));
		}

		if(!isset($tokenInfo['access_token']))
		{
			die(var_export($tokenInfo));
		}
		//print_r($tokenInfo);exit;
		//获取用户信息
		//https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
		$urlparam = array(
			'access_token='.$tokenInfo['access_token'],
			'openid='.$tokenInfo['openid'],
			'lang=zh_CN',
		);
		$url = "https://api.weixin.qq.com/sns/userinfo?".join("&",$urlparam);		
		
		//模拟post提交
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$result = curl_exec($ch);
		$userInfo = JSON::decode($result);
		
		$unid       = isset($userInfo['unionid']) ? $userInfo['unionid'] : $userInfo['openid'];
		$wechatName = trim(preg_replace('/[\x{10000}-\x{10FFFF}]/u',"",$userInfo['nickname']));
		$userInfo['nickname'] = $wechatName ? $wechatName : substr($unid,-8);
		$userInfo['name'] = $userInfo['nickname'];
		$userInfo['id'] = $unid;

		ISession::set('oauth_id',6);//模拟第三方授权登录，参考oauth表
		ISession::set('oauth_userInfo',$userInfo);
	}

	//获取用户数据
	public function getUserInfo()
	{
		$userInfo = array();
		$userInfo = ISession::get('oauth_userInfo');
		return $userInfo;
	}

	public function checkStatus($parms)
	{
		if(isset($parms['error']) || !isset($parms['code']))
		{
			return false;
		}
		else
		{
			return true;
		}
	}
}